package com.lostandfound.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.MDC;

import com.lostandfound.entity.User;

/**
 * Servlet Filter implementation class LogFilter
 */
public class LogFilter implements Filter {

	private final static double DEFAULT_USERID= Math.random()*100000.0;  

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

	       HttpServletRequest req=(HttpServletRequest)request;
	        HttpSession session= req.getSession();
	        if (session==null){
	            MDC.put("userId",DEFAULT_USERID);  
	        }
	        else{
	            User customer=(User)session.getAttribute("loginUser");
	            if (customer==null){
	                MDC.put("userId",DEFAULT_USERID);
	                MDC.put("userName",DEFAULT_USERID);
	            }
	            else
	            {
	                MDC.put("userId",customer.getId());
	                MDC.put("userName",customer.getUserCode());
	            }
	        }
	        //logger.info("test for MDC.");

	       chain.doFilter(request, response);
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {}

}
